<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
      <!--流程数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
        <el-form-item label="流程名称" prop="projectName">
          <el-input v-model="queryParams.projectName" placeholder="请输入流程名称" size="small" clearable style="width: 200px"/>
        </el-form-item>

        <el-form-item label="发布状态" prop="statusCode">
          <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
          </el-select>
        </el-form-item>
        <el-form-item label="流程备注" prop="remark">
          <el-input v-model="queryParams.remark" placeholder="请输入流程备注" size="small" clearable style="width: 150px"/>
        </el-form-item>
         <el-form-item label="更新时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
        <el-form-item>
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['saveWorkflowProject']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" v-hasPermi="['updateWorkflowProject']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" v-hasPermi="['deleteWorkflowProject']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="queryWorkflowProjectPageResList" :columns="columns"></right-toolbar>
      </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center" :selectable="checkSelectable"/>
          <el-table-column label="流程名称" sortable='custom' align="left" prop="projectName" width="250" />
     <!--     <el-table-column label="流程图片" align="center" prop="processImage" width="200" >
            <template slot-scope="scope">
              <img @click="showPreviewImage(scope.row)" v-if="scope.row.statusCode !== 'WORKFLOW_UNPUBLISHED'" :src="scope.row.processImage" style="width: 100px; height: 100px;">
              <img v-if="scope.row.statusCode === 'WORKFLOW_UNPUBLISHED'" :src="noImg" style="width: 100px; height: 100px;">
            </template>
          </el-table-column>-->
          <el-table-column label="发布状态" align="center" prop="statusName" width="200" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="流程备注" align="left" prop="remark"/>
          <el-table-column label="更新时间" align="left" prop="updateTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">

              <el-button size="mini" type="text" v-if="scope.row.statusCode === 'WORKFLOW_UNPUBLISHED'" icon="el-icon-setting"  v-hasPermi="['updateWorkflowProject']" @click="toProjectHandle(scope.row.projectId,'editorWorkflow')">设计流程</el-button>

              <el-button size="mini" type="text" icon="el-icon-view" v-if="scope.row.statusCode === 'WORKFLOW_PUBLISHED'"  v-hasPermi="['updateWorkflowProject']" @click="showPreviewImage(scope.row)">流程图例</el-button>

              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['updateWorkflowProject','deleteWorkflowProject','invalidWorkflowProject']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="scope.row.statusCode === 'WORKFLOW_UNPUBLISHED'" command="updateWorkflowProject" icon="el-icon-edit"
                                    v-hasPermi="['updateWorkflowProject']">修改</el-dropdown-item>

                  <el-dropdown-item v-if="scope.row.statusCode === 'WORKFLOW_UNPUBLISHED'" command="deleteWorkflowProject" icon="el-icon-delete"
                                    v-hasPermi="['deleteWorkflowProject']">删除</el-dropdown-item>

                  <el-dropdown-item  v-if="scope.row.statusCode === 'WORKFLOW_PUBLISHED'" command="invalidWorkflowProject" icon="el-icon-link"
                                     v-hasPermi="['invalidWorkflowProject']">弃用</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryWorkflowProjectPageResList"/>
      </el-col>
    </el-row>

    <!-- 图片预览   放在表格外面，这是个弹出框-->
    <el-dialog :visible.sync="lookDialogVisible" :modal="false" :title="previewTitle" center class="dialog-box-center">
      <el-tabs v-model="activeName">
        <el-tab-pane label="流程图例" name="workflowChart" style="height:550px;overflow-y:auto;overflow-x:auto;">
          <div style="text-align: center; 100%;height: 100%;">
            <!--<img :src="previewImage" :alt="previewTitle" class="image-item" />-->
            <!--beg-->
            <section class="dingflow-design" style="background-color: #ffffff">
              <div class="box-scale" id="box-scale" style="background-color: #ffffff">
                <nodeWrapView :nodeConfig.sync="nodeConfig" :flowPermission.sync="flowPermission"></nodeWrapView>
                <div class="end-node">
                  <div class="end-node-circle"></div>
                  <div class="end-node-text">流程结束</div>
                </div>
              </div>
            </section>
            <!--end-->
          </div>
        </el-tab-pane>

        <el-tab-pane label="流程表单" name="workflowWrite" style="height:550px;overflow-y:auto;overflow-x:auto;">
          <WorkflowFormAdd
            v-if="projectConfig.projectId"
            :key="projectConfig.projectId"
            :project-config="projectConfig"
            @submit="saveWorkflowRecord"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 图片预览 -->
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="流程名称" prop="projectName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.projectName" placeholder="请输入流程名称" maxlength="20" />
        </el-form-item>

        <el-form-item label="流程备注" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入流程备注" maxlength="200" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import noImage from '@/assets/images/noImage.gif'
  import {
    queryWorkflowProjectPageResList,
    saveWorkflowProject,
    updateWorkflowProject,
    deleteWorkflowProjectByProjectId,
    invalidWorkflowProjectByProjectId,
    queryWorkflowProcessReadImage,queryWorkflowProcessConfig} from '@/api/workflow/workflowProject'
  import WorkflowFormAdd from './workflowFormAdd'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  //默认查询参数
  let defaultQueryParams = {
    projectName: undefined,
    remark: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    page: 1,
    rows: 10
  }
  export default {
    name: "workflowModelAdmin",
    components: {
      WorkflowFormAdd
    },
    data() {
      return {
        //流程图例beg
        nodeConfig: {},
        flowPermission: [],
        //流程图例end
        projectConfig: {
          projectId: '',
          preview: false,
          showBtns: false
        },
        //流程图预览
        lookDialogVisible: false,
        previewTitle:"",
        previewImage: "",
        noImg: noImage,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 流程状态
        statusOptions: [],
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        //发起工作流默认定位
        activeName: 'workflowChart',
        // 新增修改表单校验
        addUpdateOpenRules: {
          projectName: [
            { required: true, message: "流程名称不能为空",trigger: "blur" },
          ],
          sort: [
            { required: true, message: "排序不能为空",trigger: "blur" },
          ]
        }
      }
    },
    created() {
      this.queryWorkflowProjectPageResList();
      this.initDict();
    },
    methods: {
      //预览大图
      showPreviewImage(row) {
        const projectId={projectId:row.projectId}
        queryWorkflowProcessConfig(projectId).then(res => {
          this.activeName = 'workflowChart';
          let {nodeConfig,flowPermission,projectId} = res.data
          this.nodeConfig = nodeConfig;
          this.flowPermission = flowPermission;
          this.previewTitle = row.projectName;
          this.projectConfig.projectId = row.projectId;
          this.lookDialogVisible = true;
        })
   /*     queryWorkflowProcessReadImage(projectId).then(res => {
          let data = res.data;
          this.activeName = 'workflowChart';
          this.previewImage = data?data:this.noImg;
          this.previewTitle = row.projectName;
          this.projectConfig.projectId = row.projectId;
          this.lookDialogVisible = true;
        });*/
      },
      // 是否允许选择
      checkSelectable(row) {
        return row.statusCode==='WORKFLOW_UNPUBLISHED'
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "updateWorkflowProject":
            this.handleUpdate(row);
            break;
          case "updateWorkflowProjectDesign":
            this.toProjectHandle(row.projectId,'editorWorkflow');
            break;
          case "deleteWorkflowProject":
            this.handleDelete(row);
            break;
          case "invalidWorkflowProject":
            this.handleInvalid(row);
            break;
          default:
            break;
        }
      },

      //获取数据字典
      initDict(){
        let dictArr = ["WORKFLOW_STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['WORKFLOW_STATUS']));
        });
      },
      /** 查询流程列表 */
      queryWorkflowProjectPageResList() {
        this.loading = true
        queryWorkflowProjectPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.projectId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryWorkflowProjectPageResList()
      },

      //跳转到表单设计界面
      toProjectHandle(key, type) {
        this.$router.push({path: `/project/workflow/form/${type}`, query: {key: key, active: type}})
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "新增模型";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改模型";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选流程模型?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const projectId={projectId:row.projectId}
          return deleteWorkflowProjectByProjectId(projectId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryWorkflowProjectPageResList();
        }).catch(function() {});
      },

      /** 弃用按钮操作 */
      handleInvalid(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认弃用所选流程模型?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const projectId={projectId:row.projectId}
          return invalidWorkflowProjectByProjectId(projectId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryWorkflowProjectPageResList();
        }).catch(function() {});
      },


      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.projectId !== undefined) {
              updateWorkflowProject(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryWorkflowProjectPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveWorkflowProject(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.addUpdateOpen = false
                this.toProjectHandle(response.data,'editorWorkflow')
              });
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryWorkflowProjectPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          projectId: undefined,
          projectName: undefined,
          sort: 1,
          remark: undefined
        };
        this.resetForm('form')
      },

      //发起申请流程保存功能
      saveWorkflowRecord(data) {
        console.log("预览界面模拟提交")
      },
    }
  }
</script>
<style lang="scss">
  /* 图片原图大小自适应 等比缩放 */
  .image-item {
    max-width: 100%;
    max-height: 100%;
  }

  .wrap-dialog-box {
    // element ui Dialog 对话框居中显示
    .dialog-box-center{
      text-align: center;
      &:after {
        content: "";
        display: inline-block;
        height: 100%;
        width: 0;
        vertical-align: middle;
      }
      .el-dialog{
        text-align: center;
        display: inline-block;
        margin: 0 !important;
        vertical-align: middle;
        max-width: 100%;
      }
    }
  }
  .dialog-box-center .el-dialog__body {
    overflow: auto;
  }
</style>
<style>
  @import "~@/assets/styles/workflow/workflow.css";
</style>
